﻿using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;

namespace Cms.Utilities
{
    public static class Misc
    {
        public static string RemoveParameterFromQueryString(string url, string key)
        {
            // Remove [key] from urls where [key] is the only parameter, e.g. http://test.com/media.aspx?target=somefield
            url = Regex.Replace(url, @"\?" + key + @"=[^&]*$", string.Empty, RegexOptions.IgnoreCase);

            // Remove [key] from urls where [key] is the first parameter, followed by others, e.g. http://test.com/media.aspx?target=somefield&x=y
            url = Regex.Replace(url, @"\?" + key + @"=[^&]*&", "?", RegexOptions.IgnoreCase);

            // Remove [key] from urls where [key] is not the first parameter, e.g. http://test.com/media.aspx?a=b&target=somefield&x=y
            url = Regex.Replace(url, @"&" + key + @"=[^&]*", string.Empty, RegexOptions.IgnoreCase);
            return url;
        }

        public static string GetBrowseItemDataValue(string browseItemData, string key)
        {
            foreach (string pair in
                browseItemData.Split("&".ToCharArray()).Where(
                    pair => pair.Length > 0 && pair.Substring(0, pair.IndexOf("=")).ToLower() == key.ToLower()))
            {
                return HttpUtility.UrlDecode(pair.Substring(pair.IndexOf("=") + 1));
            }
            return string.Empty;
        }
        
        public static string RenderControlHtml(Control ctrl)
        {
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);
            var htmlWriter = new HtmlTextWriter(sw);
            ctrl.RenderControl(htmlWriter);
            return sb.ToString();
        }
    }
}